package top.wsuo.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import top.wsuo.model.User;

@WebFilter(urlPatterns = {"*.jsp"})
public class LoginCheckFilter implements Filter {

    public void init(FilterConfig fConfig) {
    }

    /**
     * 拦截未登录用户的请求
     *
     * @param request  请求对象
     * @param response 相应对象
     * @param chain    过滤器链
     * @throws IOException      IO 异常
     * @throws ServletException Servlet 异常
     */
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        HttpSession session = req.getSession(false);
        String uri = req.getRequestURI();
        System.out.println(uri);
        switch (uri) {
			case "/JavaeeHomework/user/login.jsp":
            case "/JavaeeHomework/user/register.jsp":
            case "/JavaeeHomework/user/loginFailed.jsp":
            case "/JavaeeHomework/user/loginNoUser.jsp":
            case "/JavaeeHomework/error/error.jsp":
                chain.doFilter(request, response);
                break;
            default:
                if (session == null) {
                    System.out.println("用户未登录");
                    res.sendRedirect("/JavaeeHomework/user/login.jsp");
                } else if (session.getAttribute("user") == null) {
                    System.out.println("用户已经退出登录");
                    res.sendRedirect("/JavaeeHomework/user/login.jsp");
                } else {
                    chain.doFilter(request, response);
                }
                break;
        }
    }

    public void destroy() {
    }

}
